package com.lianchuang.controller;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lianchuang.entity.AccessToken;
import com.lianchuang.entity.WeChat;
import com.lianchuang.service.CoreService;
import com.lianchuang.util.Constants;
import com.lianchuang.util.PropertiesUtil;
import com.lianchuang.util.SignUtil;
import com.lianchuang.util.WeixinUtil;
import com.sun.jmx.snmp.Timestamp;

@Controller
@RequestMapping("/xxt")
public class XxtController {
	
	/**
	 * 验证微信服务器
	 * @param wc
	 * @return
	 */
	@RequestMapping(value="/api",method = RequestMethod.GET)
	@ResponseBody
	public String xxtInterface(WeChat wc){
		System.out.println("校验微信服务器请求------------");
		String signature = wc.getSignature(); 	// 微信加密签名  
        String timestamp = wc.getTimestamp(); 	// 时间戳  
        String nonce = wc.getNonce();			// 随机数  
        String echostr = wc.getEchostr();		// 随机字符串  
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
            return echostr;  
        } else {  
            System.out.println("不是微信服务器发来的请求,请小心!");  
            return null;
        }  
	}
	
	/**
	 * 处理用户消息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/api",method = RequestMethod.POST)
	public void getWeiXinMessage(HttpServletRequest request, HttpServletResponse response) throws Exception{
		System.out.println("用户发来一条消息，正在处理----------当前时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        request.setCharacterEncoding("UTF-8");  //微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
        response.setCharacterEncoding("UTF-8"); //在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
        String respMessage = CoreService.processRequest(request);//调用CoreService类的processRequest方法接收、处理消息，并得到处理结果；
        // 响应消息
        PrintWriter out = response.getWriter();
        out.print(respMessage);
        out.close();
	}
	
	/**
	 * 生成自定义菜单
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/createMenu",method = RequestMethod.GET)
	@ResponseBody
	public void createMenu(HttpServletRequest request, HttpServletResponse response) throws Exception{
		System.out.println("创建菜单，正在处理----------当前时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        request.setCharacterEncoding("UTF-8");  //微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
        response.setCharacterEncoding("UTF-8"); //在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
        AccessToken token = getToken();
		String menu = "{\"button\":[{\"type\":\"click\",\"name\":\"项目管理\",\"key\":\"20_PROMANAGE\"},{\"type\":\"click\",\"name\":\"机构运作\",\"key\":\"30_ORGANIZATION\"},{\"name\":\"日常工作\",\"sub_button\":[{\"type\":\"click\",\"name\":\"待办工单\",\"key\":\"01_WAITING\"},{\"type\":\"click\",\"name\":\"已办工单\",\"key\":\"02_FINISH\"},{\"type\":\"click\",\"name\":\"我的工单\",\"key\":\"03_MYJOB\"},{\"type\":\"click\",\"name\":\"公告消息箱\",\"key\":\"04_MESSAGEBOX\"},{\"type\":\"view\",\"name\":\"绑定帐号\",\"url\":\"http://123.57.158.29/weixinMVC/xxt/bindUser\"}]}]}";
		String url = Constants.CREATE_MENU_URL.replace("ACCESS_TOKEN", token.getAccessToken());
		String str = WeixinUtil.httpRequest(url, "POST", menu);
		System.out.println("创建成功！"+str);
	}
	
	/**
	 * 删除自定义菜单
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteMenu",method = RequestMethod.GET)
	@ResponseBody
	public void deleteMenu(HttpServletRequest request, HttpServletResponse response) throws Exception{
		System.out.println("删除菜单，正在处理----------当前时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        AccessToken token = getToken();
		String url = Constants.DELETE_MENU_URL.replace("ACCESS_TOKEN", token.getAccessToken());
		String str = WeixinUtil.httpRequest(url, "GET", null);
		System.out.println("删除成功！"+str);
	}
	
	
	/**
	 * 从本地文件获取token，若过期则重新获取
	 * @return
	 */
	public AccessToken getToken(){
		try {
			AccessToken token = new AccessToken();
			//获取accessToken之前判断文件里有没有，没有重新获取，填写过期时间，有判断时间有没有过期
			PropertiesUtil putil=new PropertiesUtil("D:\\apache-tomcat-6.0.37\\wtpwebapps\\weixinMVC\\WEB-INF\\classes\\conf\\config.properties");
//			PropertiesUtil putil=new PropertiesUtil("C:\\Program Files\\Apache Software Foundation\\Tomcat 7.0\\webapps\\weixinMVC\\WEB-INF\\classes\\conf\\config.properties");
			Long overduetime = Long.parseLong(putil.getProperty("OVERDUE_ACCESS_TOKEN_TIME"));
			Timestamp s = new Timestamp();
			if(s.getDateTime()>overduetime){
				//超时从新获取accessToken
				token = WeixinUtil.getAccessToken2(Constants.APPID, Constants.SECRET);
				putil.writeProperties("OVERDUE_ACCESS_TOKEN_TIME", String.valueOf(s.getDateTime()+Constants.EFFECTIVE_TIME));
				putil.writeProperties("ACCESS_TOKEN", token.getAccessToken());
			}else{
				System.out.println("token:"+putil.getProperty("ACCESS_TOKEN"));
				token.setAccessToken(putil.getProperty("ACCESS_TOKEN"));
			}
			return token;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) {
		String signature = "E06364BB47149AAD409BFC1336A327E401298FBC"; // 微信加密签名  
        String timestamp = "12131"; // 时间戳  
        String nonce = "32432";// 随机数  
        String echostr = "fddsads";// 随机字符串  
  
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
        	System.out.println("接入成功");
        } else {  
            System.out.println("不是微信服务器发来的请求,请小心!");  
        }  
	}
}
